<template>
  <view class="car-maintenance-page">
    <!-- 地图容器 - 占据上方2/3区域 -->
    <view class="map-container" id="mapContainer">
      <!-- H5地图 -->
      <!-- #ifdef H5 -->
      <view id="mapContainer" style="width: 100%; height: 100%;"></view>
      <!-- #endif -->
      
      <!-- 小程序地图 -->
      <!-- #ifdef MP-WEIXIN -->
      <map
        id="map"
        :longitude="longitude"
        :latitude="latitude"
        :markers="markers"
        :show-location="true"
        style="width: 100%; height: 100%;"
      ></map>
      <!-- #endif -->
      
      <!-- 附近门店按钮 -->
      <view class="nearby-store-btn" @click="goNearbyStores">
        <text>附近门店></text>
        <view class="btn-arrow">↓</view>
      </view>
    </view>
    
    <!-- 门店信息卡片 - 占据底部1/3区域 -->
    <view class="store-card">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">正在加载门店信息...</text>
      </view>
      
      <!-- 门店信息 -->
      <view v-else-if="currentStore.name" class="store-info-container">
        <view class="store-header">
          <view class="store-name">{{currentStore.name}}</view>
          <text class="store-distance">{{currentStore.distance}}</text>
        </view>
      
      <!-- 门店切换指示器 -->
      <view class="store-indicator">
        <view 
          class="indicator-dot" 
          :class="{ 'active': currentStore.name === store.name }" 
          v-for="(store, index) in storeList" 
          :key="index"
          @click="switchStore(index)"
        ></view>
      </view>
      
      <view class="store-content">
        <view class="store-info">
          <view class="rating-row">
            <view class="store-rating">
              <text class="star filled" v-for="i in Math.floor(currentStore.rating)" :key="i">★</text>
              <text class="star" v-for="i in (5 - Math.floor(currentStore.rating))" :key="i + Math.floor(currentStore.rating)">★</text>
              <text class="rating-score">{{currentStore.rating}}分</text>
            </view>
          </view>
          
          <view class="store-details">
            <view class="business-hours">营业时间: {{currentStore.businessHours}}</view>
            <view class="store-address">{{currentStore.address}}</view>
            <view class="store-services" v-if="currentStore.description">
              <text class="services-label">服务介绍:</text>
              <text class="services-text">{{currentStore.description}}</text>
            </view>
          </view>
        </view>
        
        <view class="store-thumbnail">
          <image src="@/img/车辆维修/维修厂1.jpeg" mode="aspectFill"></image>
        </view>
      </view>
      
        <view class="store-actions">
          <button class="contact-btn" @click="contactStore(currentStore.phone)">联系门店</button>
          <button class="book-btn" @click="bookStore(currentStore)">立即预定</button>
        </view>
      </view>
      
      <!-- 无数据提示 -->
      <view v-else class="no-data-container">
        <text class="no-data-text">附近暂无门店信息</text>
      </view>
    </view>
    
    <!-- 自定义电话弹窗 - 与原型图完全一致 -->
    <view class="phone-dialog-overlay" v-if="showPhoneDialog" @click="closePhoneDialog">
      <view class="phone-dialog" @click.stop>
        <view class="phone-number">{{currentStore.phone}}</view>
        <button class="call-btn" @click="makePhoneCall">呼叫</button>
        <button class="cancel-btn" @click="closePhoneDialog">取消</button>
      </view>
    </view>
	</view>
</template>

<script>
// #ifdef H5
import AMapLoader from '@amap/amap-jsapi-loader';
// #endif

// #ifdef MP-WEIXIN
import amap from '@/common/amap-wx.js';
// #endif

import { maintenanceMerchantApi } from '@/api/index.js';

	export default {
		data() {
			return {
      showPhoneDialog: false, // 控制自定义电话弹窗显示
      currentStore: {},
      storeList: [],
      map: null,
      amapKey: '8477719e461b7195529912991c106c9a',
      longitude: 113.230000, // 默认经纬度
      latitude: 35.250000,   // 默认经纬度
      markers: [],
      loading: false,
      serviceTypeId: 2 // 汽车保养服务类型ID，根据实际情况调整
    };
  },
  
  onLoad() {
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: '汽车保养'
    });
  },
  
  onReady() {
    this.initMap();
  },
  
  methods: {
    // 获取附近门店数据
    async getNearbyStores() {
      try {
        this.loading = true;
        console.log('开始获取门店数据，当前位置:', this.longitude, this.latitude);
        
        const response = await maintenanceMerchantApi.getMerchantsByServiceType(this.serviceTypeId, {
          longitude: this.longitude,
          latitude: this.latitude
        });
        
        console.log('API响应:', response);
        
        if (response.code === 200 && response.data) {
          const merchants = response.data;
          console.log('获取到的商户数据:', merchants);
          
          if (merchants && merchants.length > 0) {
            this.storeList = merchants.map(merchant => this.formatStoreData(merchant));
            
            if (this.storeList.length > 0) {
              this.currentStore = { ...this.storeList[0] };
              console.log('设置当前门店:', this.currentStore);
            }
            
            this.updateMapMarkers();
          } else {
            // 如果按服务类型没有找到门店，尝试获取附近所有门店
            console.log('按服务类型未找到门店，尝试获取附近门店');
            await this.getNearbyAllStores();
          }
        } else {
          console.log('API返回错误:', response);
          // 如果API出错，也尝试获取附近所有门店
          await this.getNearbyAllStores();
        }
      } catch (error) {
        console.error('获取门店数据失败:', error);
        // 如果出现网络错误，也尝试获取附近所有门店
        await this.getNearbyAllStores();
      } finally {
        this.loading = false;
      }
    },

    // 获取附近所有门店（备用方法）
    async getNearbyAllStores() {
      try {
        console.log('尝试获取附近所有门店');
        
        const response = await maintenanceMerchantApi.getNearbyMerchants({
          longitude: this.longitude,
          latitude: this.latitude,
          radius: 50.0 // 50公里范围内
        });
        
        console.log('附近门店API响应:', response);
        
        if (response.code === 200 && response.data && response.data.length > 0) {
          const merchants = response.data;
          console.log('获取到的附近门店数据:', merchants);
          
          this.storeList = merchants.map(merchant => this.formatStoreData(merchant));
          
          if (this.storeList.length > 0) {
            this.currentStore = { ...this.storeList[0] };
            console.log('设置当前门店（附近门店）:', this.currentStore);
          }
          
          this.updateMapMarkers();
        } else {
          console.log('附近也没有找到门店');
          uni.showToast({
            title: '附近暂无门店',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取附近门店失败:', error);
        uni.showToast({
          title: '获取门店信息失败',
          icon: 'none'
        });
      }
    },

    // 格式化门店数据
    formatStoreData(merchant) {
      console.log('正在格式化商户数据:', merchant);
      
      const lng = parseFloat(merchant.longitude) || this.longitude;
      const lat = parseFloat(merchant.latitude) || this.latitude;
      
      // 格式化营业时间
      let businessHours = '营业时间未设置';
      if (merchant.startTime && merchant.endTime) {
        businessHours = `周一至周日 ${merchant.startTime}-${merchant.endTime}`;
      } else if (merchant.businessHours) {
        businessHours = merchant.businessHours;
      }
      
      const formattedData = {
        id: merchant.id,
        name: merchant.name || '未知门店',
        distance: this.calculateDistance(lng, lat),
        time: this.calculateTime(lng, lat),
        rating: merchant.rate || 5, // 使用rate字段，这是数据库中的实际字段
        businessHours: businessHours,
        address: merchant.address || '地址未设置',
        phone: this.generateDefaultPhone(merchant.id), // 数据库中没有phone字段，生成默认电话
        longitude: lng,
        latitude: lat,
        image: merchant.image || require("@/img/车辆维修/维修厂1.jpeg"),
        services: merchant.services || [],
        description: merchant.description || '暂无介绍'
      };
      
      console.log('格式化后的数据:', formattedData);
      return formattedData;
    },

    // 计算距离（简单计算，实际项目中可以使用更精确的算法）
    calculateDistance(lng, lat) {
      const R = 6371; // 地球半径（公里）
      const dLat = (lat - this.latitude) * Math.PI / 180;
      const dLng = (lng - this.longitude) * Math.PI / 180;
      const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(this.latitude * Math.PI / 180) * Math.cos(lat * Math.PI / 180) *
                Math.sin(dLng/2) * Math.sin(dLng/2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      const distance = R * c * 1000; // 转换为米
      
      if (distance < 1000) {
        return Math.round(distance) + 'm';
      } else {
        return (distance / 1000).toFixed(1) + 'km';
      }
    },

    // 计算预估时间（简单估算）
    calculateTime(lng, lat) {
      const distance = this.calculateDistance(lng, lat);
      const distanceNum = parseFloat(distance);
      
      if (distance.includes('m')) {
        return Math.max(1, Math.round(distanceNum / 100)) + '分';
      } else {
        return Math.max(1, Math.round(distanceNum * 2)) + '分';
      }
    },

    // 更新地图标记
    updateMapMarkers() {
      this.markers = this.storeList.map((store, index) => ({
        id: index,
        longitude: store.longitude,
        latitude: store.latitude,
        title: store.name,
        iconPath: '/static/marker.png',
        width: 30,
        height: 30
      }));
    },

    // 生成默认电话号码（基于商户ID）
    generateDefaultPhone(merchantId) {
      // 为不同的商户生成不同的默认电话
      const phoneMap = {
        15: '18893029302', // 伟业汽车保养场(人民路店)
        16: '18893029303', // 速修汽车保养中心  
        17: '18893029304'  // 专业汽车保养连锁店
      };
      
      return phoneMap[merchantId] || `1889302930${merchantId % 10}`;
    },

    initMap() {
      // 先获取位置，然后初始化地图和获取门店数据
      this.getCurrentLocation().then(() => {
        this.initMapWithLocation();
        this.getNearbyStores();
      });
    },

    // 获取当前位置
    getCurrentLocation() {
      return new Promise((resolve) => {
        // #ifdef H5
        // 尝试获取HTML5定位
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              this.longitude = position.coords.longitude;
              this.latitude = position.coords.latitude;
              console.log('HTML5定位成功:', this.longitude, this.latitude);
              resolve();
            },
            (error) => {
              console.error('HTML5定位失败:', error);
              console.log('使用默认经纬度:', this.longitude, this.latitude);
              resolve();
            },
            { timeout: 10000, enableHighAccuracy: true }
          );
        } else {
          console.log('浏览器不支持定位，使用默认经纬度');
          resolve();
        }
        // #endif

        // #ifdef MP-WEIXIN
        uni.getLocation({
          type: 'gcj02',
          success: (res) => {
            this.longitude = res.longitude;
            this.latitude = res.latitude;
            console.log('小程序定位成功:', this.longitude, this.latitude);
            resolve();
          },
          fail: (err) => {
            console.error('小程序定位失败:', err);
            console.log('使用默认经纬度:', this.longitude, this.latitude);
            resolve();
          }
        });
        // #endif
      });
    },

    // 使用位置信息初始化地图
    initMapWithLocation() {
      // #ifdef H5
      AMapLoader.load({
        key: this.amapKey,
        version: '2.0',
        plugins: ['AMap.Marker', 'AMap.Geolocation']
      }).then((AMap) => {
        this.map = new AMap.Map('mapContainer', {
          zoom: 16,
          center: [this.longitude, this.latitude]
        });
        
        this.addStoreMarkers(AMap);
      }).catch(e => {
        console.error('H5地图加载失败:', e);
      });
      // #endif
      
      // #ifdef MP-WEIXIN
      // 小程序地图会通过markers属性显示标记
      // #endif
    },
    
    addStoreMarkers(AMap) {
      // #ifdef H5
      if (this.map && this.storeList.length > 0) {
        this.storeList.forEach((store, index) => {
          const marker = new AMap.Marker({
            position: [store.longitude, store.latitude],
            title: store.name,
            label: {
              content: store.name,
              offset: new AMap.Pixel(0, 30)
            }
          });
          marker.setMap(this.map);
        });
      }
      // #endif
      
      // #ifdef MP-WEIXIN
      // 小程序地图标记通过updateMapMarkers方法更新
      // #endif
    },
				
    goNearbyStores() {
      uni.navigateTo({
        url: "/pages/nearbyCarMaintenance/nearbyCarMaintenance",
        success: () => {
          console.log('跳转到汽车保养附近门店页面成功');
        },
        fail: (err) => {
          console.error('跳转到汽车保养附近门店页面失败：', err);
        }
      });
    },
    
    contactStore(phoneNumber) {
      console.log('联系门店，电话号码:', phoneNumber);
      
      const formattedPhone = phoneNumber.replace(/[^\d-]/g, '');
      if (!formattedPhone) {
        uni.showToast({ title: '电话号码格式错误', icon: 'none' });
        return;
      }
    
      // 显示自定义电话弹窗，避免系统默认的重复取消按钮
      this.showPhoneDialog = true;
    },
    
    // 关闭电话弹窗
    closePhoneDialog() {
      this.showPhoneDialog = false;
    },
    
    // 拨打电话
    makePhoneCall() {
      const formattedPhone = this.currentStore.phone.replace(/[^\d-]/g, '');
      console.log('开始拨打电话:', formattedPhone);
      
      uni.makePhoneCall({
        phoneNumber: formattedPhone,
        success: () => {
          console.log('拨打电话成功');
          this.closePhoneDialog();
        },
        fail: (err) => {
          console.error('拨打电话失败：', err);
          uni.showToast({ 
            title: '拨打电话失败', 
            icon: 'none' 
          });
        }
      });
    },
				
    bookStore(store) {
      console.log('准备跳转到汽车保养门店详情页面，门店数据:', store);
      
      // 跳转到汽车保养门店详情页面，传递门店数据
      uni.navigateTo({
        url: `/pages/carMaintenanceDetails/carMaintenanceDetails?storeData=${encodeURIComponent(JSON.stringify(store))}`,
        success: () => {
          console.log('跳转到汽车保养门店详情页面成功');
        },
        fail: (err) => {
          console.error('跳转到汽车保养门店详情页面失败：', err);
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 切换当前门店
    switchStore(storeIndex) {
      if (this.storeList[storeIndex]) {
        this.currentStore = { ...this.storeList[storeIndex] };
        console.log('切换到门店:', this.currentStore.name);
      }
    }
  }
};


</script>

<style scoped>
.car-maintenance-page {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 地图容器样式 - 占据上方2/3区域 */
.map-container {
  width: 100%;
  height: calc(100vh - 200rpx);
  background-color: #e8e8e8;
  position: relative;
}

/* 附近门店按钮样式 */
.nearby-store-btn {
  position: absolute;
  top: 50%;
  right: 30rpx;
  background-color: #666;
  color: #fff;
  padding: 20rpx 30rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10;
}

.btn-arrow {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #007AFF;
}

/* 门店信息卡片样式 - 占据底部1/3区域 */
.store-card {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx 30rpx 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  position: relative;
}

.store-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.store-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.2;
}

.store-distance {
  font-size: 28rpx;
  color: #007AFF;
  font-weight: bold;
}

.store-indicator {
  display: flex;
  justify-content: center;
  gap: 10rpx;
  margin: 15rpx 0;
}

.indicator-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #ddd;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.indicator-dot.active {
  background-color: #007AFF;
}

.store-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 25rpx;
}

.store-info {
  flex: 1;
  margin-right: 25rpx;
}

.rating-row {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.store-rating {
  display: flex;
  align-items: center;
  margin-right: 12rpx;
}

.star {
  font-size: 26rpx;
  color: #ddd;
  margin-right: 3rpx;
}

.star.filled {
  color: #FFD700;
}

.rating-score {
  font-size: 24rpx;
  color: #666;
  margin-left: 8rpx;
}



.store-details {
  display: flex;
  flex-direction: column;
}

.business-hours {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.store-address {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
}

.store-services {
  display: flex;
  align-items: center;
  margin-top: 8rpx;
}

.services-label {
  font-size: 24rpx;
  color: #666;
  margin-right: 8rpx;
}

.services-text {
  font-size: 24rpx;
  color: #007AFF;
}

/* 门店缩略图 */
.store-thumbnail {
  width: 100rpx;
  height: 120rpx;
  border-radius: 8rpx;
  overflow: hidden;
  flex-shrink: 0;
  margin-top: 5rpx;
}

.store-thumbnail image {
  width: 100%;
  height: 100%;
}

.store-actions {
  display: flex;
  gap: 15rpx;
  margin-bottom: 0;
}

.contact-btn, .book-btn {
  flex: 1;
  height: 75rpx;
  border-radius: 35rpx;
  font-size: 28rpx;
  border: none;
}

.contact-btn {
  background-color: #f0f2f5;
  color: #333;
}

.book-btn {
  background-color: #ff4757;
  color: #fff;
}

/* 自定义电话弹窗样式 - 与原型图完全一致 */
.phone-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.phone-dialog {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  overflow: hidden;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.phone-number {
  text-align: center;
  font-size: 28rpx;
  color: #333;
  padding: 40rpx 30rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e5e5e5;
}

.call-btn, .cancel-btn {
  height: 110rpx;
  font-size: 28rpx;
  border: none;
  width: 100%;
  background-color: #fff;
  color: #333;
  border-bottom: 1rpx solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  border-bottom: none;
}

.call-btn:active, .cancel-btn:active {
  background-color: #f5f5f5;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 无数据状态样式 */
.no-data-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
}

.no-data-text {
  font-size: 28rpx;
  color: #999;
}
</style>
